package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.BusinessAssert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.query.UserInfoQuery;
import com.atguigu.srb.utils.JwtUtils;
import com.atguigu.common.util.MD5;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.mapper.UserLoginRecordMapper;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.UserLoginRecord;
import com.atguigu.srb.core.pojo.vo.LoginVO;
import com.atguigu.srb.core.pojo.vo.RegisterVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author 龙龙龙
 * @since 2022-01-21
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserLoginRecordMapper userLoginRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(RegisterVO registerVO) {

        //校验验证码
        String code = registerVO.getCode();
        String mobile = registerVO.getMobile();

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("mobile",mobile);
        Integer integer = baseMapper.selectCount(queryWrapper);
        //手机号不能重复注册
        BusinessAssert.isTrue(integer == 0 ,ResponseEnum.MOBILE_EXIST_ERROR);

        //查询redis
        String codeFromCache = (String) redisTemplate.opsForValue().get("srb:sms:code"+mobile);
        System.out.println(codeFromCache);
        //验证码为空
        BusinessAssert.notNull(codeFromCache, ResponseEnum.CODE_ERROR);
        //验证码不正确
        BusinessAssert.equals(code, codeFromCache, ResponseEnum.CODE_ERROR);

        //将用户的信息保存到数据库
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(registerVO, userInfo);
        userInfo.setNickName(mobile);
        userInfo.setName(mobile);
        userInfo.setPassword(MD5.encrypt(userInfo.getPassword()));
        userInfo.setStatus(1); //正常
        //设置一张静态资源服务器上的头像图片
        userInfo.setHeadImg("https://lllong.oss-cn-shenzhen.aliyuncs.com/hexoImage/aluba.png");
        baseMapper.insert(userInfo);

        System.out.println(userInfo);
        //生成用户的账号信息
        UserAccount userAccount = new UserAccount();
        Long id = userInfo.getId();
        userAccount.setUserId(id);
        System.out.println(userAccount);
        userAccountMapper.insert(userAccount);

        return true;
    }

    @Override
    @Transactional( rollbackFor = {Exception.class})
    public UserInfoVO login(LoginVO loginVO, String ip) {
        String mobile = loginVO.getMobile();
        String password = MD5.encrypt(loginVO.getPassword());
        Integer userType = loginVO.getUserType();

        //用户是否存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        BusinessAssert.notNull(userInfo,ResponseEnum.LOGIN_MOBILE_ERROR);

        //密码是否正确
        BusinessAssert.equals(password,userInfo.getPassword(),ResponseEnum.LOGIN_PASSWORD_ERROR);

        //用户是否可用
        BusinessAssert.equals(userInfo.getStatus(),1,ResponseEnum.LOGIN_LOKED_ERROR);

        //生成令牌
        UserInfoVO userInfoVO = new UserInfoVO();
        String token = JwtUtils.createToken(userInfo.getId(),userInfo.getName()); //JWT算法工具类
        userInfoVO.setName(userInfo.getName());
        userInfoVO.setNickName(userInfo.getNickName());
        userInfoVO.setHeadImg(userInfo.getHeadImg());
        userInfoVO.setMobile(userInfo.getMobile());
        userInfoVO.setUserType(userType);
        userInfoVO.setToken(token);


        //记录登录日志
        UserLoginRecord loginRecord = new UserLoginRecord();
        loginRecord.setUserId(userInfo.getId());
        loginRecord.setIp(ip);
        userLoginRecordMapper.insert(loginRecord);

        return userInfoVO;
    }

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> pageParam, UserInfoQuery userInfoQuery) {
        String mobile = userInfoQuery.getMobile();
        Integer status = userInfoQuery.getStatus();
        Integer userType = userInfoQuery.getUserType();

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();

        if(userInfoQuery == null){
            return baseMapper.selectPage(pageParam, null);
        }

        userInfoQueryWrapper
                .eq(StringUtils.isNotBlank(mobile), "mobile", mobile)
                .eq(status != null, "status", userInfoQuery.getStatus())
                .eq(userType != null, "user_type", userType);
        return baseMapper.selectPage(pageParam, userInfoQueryWrapper);
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    @Override
    public boolean checkMobile(String mobile) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        Integer integer = baseMapper.selectCount(queryWrapper);
        System.out.println(integer);
        return integer > 0;
    }
}
